package org.jiuling.validation.spring.handle;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.jiuling.basics.exception.BasicsException;
import org.jiuling.basics.util.ClassUtil;
import org.jiuling.basics.validation.*;
import org.jiuling.validation.spring.annotation.Coexist;

/**
 * 共存校验
 * @author 紫灵
 * @date 2024年12月28日 00时49分40秒
 */
public class CoexistValidator  implements ConstraintValidator<Coexist, Object> {

    /** 主参数名 */
    private String mainParam;
    /** 子参数 */
    private String[] subParams;

    @Override
    public void initialize(Coexist constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        this.mainParam = constraintAnnotation.mainParam();
        this.subParams = constraintAnnotation.subParams();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (ObjectVerify.isNull(value) ||
                StringVerify.isBlank(mainParam) ||
                ArrayVerify.isEmpty(subParams)) return true;

        try {
            Object mainParamValue = ClassUtil.getFieldValue(value, mainParam);
            // 判断主参数是否为空
            if (ObjectVerify.baseTypeIsBlank(mainParamValue)) return true;

            // 便利子参数
            for (String subParam : subParams) {
                Object subParamValue = ClassUtil.getFieldValue(value, subParam);
                // 如果子参数中存在空白则返回false
                if (ObjectVerify.baseTypeIsBlank(subParamValue)) return false;
            }
        } catch (BasicsException ignored) {
        }
        return true;
    }
}
